package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * Author:huzhongkui
 * Date: 2025-01-13 星期一 10:26:10
 * Description: 微信自动配置类型
 */
@Configuration
@EnableConfigurationProperties(WxProperties.class)
public class WxAutoConfiguration {

    /**
     * 定义一个WxMaService的Bean对象
     */
    @Bean
    public WxMaService wxMaService(WxProperties wxProperties) {

        // 1.定义一个WxMaService的实现类对象
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();

        // 2.给WxMaServiceImpl对象属性赋值
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxProperties.getAppSecret());
        wxMaService.setWxMaConfig(wxMaDefaultConfig);
        // 3.返回出去
        return wxMaService;

    }

    /**
     * 定义一个RsaSigner的Bean对象
     */
    @Bean
    public RsaSigner rsaSigner() {

        // 1.获取到 tingshu.jks证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");

        // 2.获取到钥匙工厂对象
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());

        // 3.获取钥匙对
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());

        // 4.获取私钥
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();

        return new RsaSigner(aPrivate);
    }


}
